import uploadApi from "@/apis/uploadApi";
import Editor from "@toast-ui/editor"
export default class{
    editor:Editor
    isFullscreen: boolean = false
    constructor(el:string,initialValue:string,public height:string){
       this.editor = new Editor({
            el: document.querySelector(el)as HTMLElement,
            previewStyle: 'vertical',
            height: height,
            initialValue: initialValue,
            initialEditType:'markdown' ,
            toolbarItems:this.toolbar() as [],
            
          });
       this.ImageHook()
       
    }

 
  private  toolbar(){
   return [
      ['heading', 'bold', 'italic', 'strike'],
      ['hr', 'quote'],
      ['ul', 'ol', 'task', 'indent', 'outdent'],
      ['table', 'image', 'link'],
      ['code', 'codeblock'],
      [{
        el: this.fullscreen(),
        command: 'bold',
        tooltip: 'Custom Bold'
      }]
    ]
    }


    private fullscreen(){
         const button =document.createElement("button") as HTMLButtonElement
         button.innerHTML="全屏"
         button.style.margin="0"
         button.addEventListener("click",()=>{
          this.toggleFullscreen()
            })

            document.documentElement.addEventListener('keyup', (event: KeyboardEvent) => {
              if (event.key == 'Escape' && this.isFullscreen) {
                this.toggleFullscreen()

              }
          
            })
         return button
    }

    private toggleFullscreen() {
      const ui = document.querySelector('.toastui-editor-defaultUI') as HTMLDivElement
      ui.classList.toggle('fullscreen')
      //获取焦点
      this.editor.focus()
      this.isFullscreen = !this.isFullscreen
  
      if (this.isFullscreen === false) {
        this.editor.setHeight(this.height)
      } else {
        this.editor.setHeight('100vh')
      }
    }


     private ImageHook(){
      //移除上传图片转换base64的钩子
        this.editor.removeHook("addImageBlobHook")
        //添加自定义的钩子
        this.editor.addHook("addImageBlobHook",async(blob:any,callback:Function)=>{
           //上传
             const form = new  FormData()
             form.append("file",blob,blob.name)
            


            //  调用上传的接口
           const response= await   uploadApi.loadInfo(form)
         console.log(  response.data.url);

         //将url写到编辑器当中
         callback(response.data.url,blob.name)
        })
     }
}